package com.zxy.controller;

import cn.dsna.util.images.ValidateCode;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zxy.model.AdminInfo;
import com.zxy.model.ConsumerInfo;
import com.zxy.service.AdminService;
import com.zxy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
public class UserController {
    
    @Resource
    private Gson gson;
    @Resource
    private JsonObject result;
    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;
    @Resource
    private ConsumerInfo consumerInfo;
    @Resource
    private AdminInfo adminInfo;
    
    @RequestMapping("index")
    public String index(){
        return "index";
    }
    @RequestMapping("personalMusic")
    public String personalMusic(){
        return "personalMusic";
    }
    @RequestMapping("adminLogin")
    public String adminLogin(){
        return "adminLogin";
    }
    @RequestMapping("userLogin")
    public String userLogin(){
        return "userLogin";
    }
    @RequestMapping("userRegister")
    public String userRegister(){
        return "userRegister";
    }
    @RequestMapping("deleteSuccess")
    public String deleteSuccess(){
        return "deleteSuccess";
    }
    @RequestMapping("toPlayMusic")
    public String toPlayMusic(){
        return "toPlayMusic";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
        return "toLogin";
    }
    @RequestMapping("musicList")
    public String musicList(){
        return "musicList";
    }
    @RequestMapping("error")
    public String error(){
        return "error";
    }
    @RequestMapping("success")
    public String success(){
        return "success";
    }
    
    @RequestMapping("getAllMusic")
    public void getAllMusic(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.getSession().setAttribute("musicList",userService.getAllMusic());
        response.getWriter().write(gson.toJson(userService.getAllMusic()));
    }
    
    @RequestMapping("code")
    public void validateCode(HttpServletResponse response,HttpSession session){
        try {
            response.setHeader("pragma", "no-cache");
            response.setHeader("cache-control", "no-cache");
            response.setHeader("expires", "0");
            ValidateCode vc= new ValidateCode(120,36,4,4);
            vc.write(response.getOutputStream());
            String code =vc.getCode().toLowerCase();
            session.setAttribute("code",code);
            String a= (String) session.getAttribute("code");
            System.out.println(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @RequestMapping(value = "login",method={ RequestMethod.POST})
    public void login(@RequestBody HashMap<String,String> map, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String adminInfoJsonString = gson.toJson(map, HashMap.class);
        //JsonObject jsonObject = new JsonParser().parse(adminInfoJsonString).getAsJsonObject();
        boolean b = false;
        //根据接收到的type类型，来判断是普通用户还是管理员，1代表管理员，0代表普通用户
        //int i = jsonObject.get("type").getAsInt();
        int i = Integer.parseInt(map.get("type"));
        adminInfo.setLoginName(map.get("loginName"));
        adminInfo.setPwd(map.get("pwd"));
        if(i == 1){
            b = adminService.checkAdminInfo(adminInfo);
        }else if(i == 0){
            //首先验证验证码是否正确
            if(map.get("code").equalsIgnoreCase(request.getSession().getAttribute("code").toString())){
                consumerInfo = gson.fromJson(adminInfoJsonString, ConsumerInfo.class);
                b = userService.checkConsumerInfo(consumerInfo);
            }else{
                response.setContentType("text/json;charset=utf-8");
                result.addProperty("code","false");
                response.getWriter().write(result.toString());
                return;
            }
        }
        
        //根据不同的用户，登陆成功后跳转的页面也不同，普通用户是personalMusic.jsp，管理员用户是musicList.jsp
        if(b){
            response.setContentType("text/json;charset=utf-8");
            result.addProperty("result","true");
            if(i == 1){
                result.addProperty("url","musicList.jsp");
                request.getSession().setAttribute("admin",adminInfo);
            }
            if(i == 0){
                request.getSession().setAttribute("loginName",map.get("loginName"));
                result.addProperty("url","personalMusic");
            }
            response.getWriter().write(result.toString());
        }else {
            response.setContentType("text/json;charset=utf-8");
            result.addProperty("result","false");
            result.addProperty("url","error.jsp");
            response.getWriter().write(result.toString());
        }
        
        
    }
    
    @RequestMapping(value = "checkUserName",method={ RequestMethod.POST})
    public void checkUserName(@RequestBody HashMap<String,String> map, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //String jsonString=gson.toJson(map,HashMap.class);
        //JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
        //String loginName = jsonObject.get("userName").getAsString();
        String loginName = map.get("userName");
        boolean b = userService.checkUserName(loginName);
        if(b){
            result.addProperty("result","false");
            response.getWriter().write(result.toString());
        }else{
            result.addProperty("result","true");
            response.getWriter().write(result.toString());
        }
        
    }
    @RequestMapping(value = "register",method={ RequestMethod.POST})
    public void userRegister(@RequestBody HashMap<String,String> map, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String jsonString=gson.toJson(map,HashMap.class);
        
        
        
        
        JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
        if(!jsonObject.get("code").getAsString().equalsIgnoreCase(request.getSession().getAttribute("code").toString())){
            result.addProperty("code","false");
            response.getWriter().write(result.toString());
            return;
        }
        
        //解析用户注册发送的json数据
        consumerInfo = gson.fromJson(jsonString, ConsumerInfo.class);
        boolean b = userService.insertConsumerInfo(consumerInfo);
        if(b){
            request.getSession().setAttribute("loginName",jsonObject.get("loginName").getAsString());
            response.setContentType("text/json; charset=utf-8");
            result.addProperty("result","true");
            result.addProperty("url","/success");
            response.getWriter().write(result.toString());
        }else {
            result.addProperty("result","false");
            response.getWriter().write(result.toString());
        }
    }
    
    @RequestMapping(value = "download",method={ RequestMethod.POST,RequestMethod.GET})
    public void download(HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String msg;
        //得到要下载的文件名
        String fileName = request.getParameter("musicName");
        //获取相对路径music的真实路径
        String webRealPath=request.getServletContext().getRealPath("music");
        //文件的完整路径
        String fullPath = webRealPath+"/"+fileName;
        File file = new File(fullPath);
        if(!file.exists()){
            request.setAttribute("message","资源文件不存在!");
            request.getRequestDispatcher("personalMusic").forward(request, response);
            return;
        }
        //设置响应头，控制浏览器下载该文件，URL必须使用URLEncoder编码，否则浏览器地址栏中的URL会乱码     空格被URLEncoder编码后会变成+，替换，空格对应的URL编码表：%20
        response.setHeader("content-disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8").replace("+","%20"));
        //读取要下载的文件，保存到文件输入流
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(fullPath));
        OutputStream out = response.getOutputStream();
        byte buffer[] = new byte[2048];
        int len = 0;
        while((len=in.read(buffer))>0){
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }
    //
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate();
        return "redirect:index";
    }
}
